Opening and Closing Files Using open() in Python
Course: Python Training
Topic: Opening and Closing Files Using open()
Course Link: Python Training Course at JustAcademy
Demo Link: Register for a Free Course Demo
JustAcademy Homepage: Visit JustAcademy
1. Introduction to File Handling in Python
File handling is an important Python programming concept that allows applications to store, retrieve, update, and manage information in files. Instead of keeping data only in variables while a program runs, developers can save information permanently and access it later.
Python provides the built-in open() function to open files. This function creates a file object that can be used to read data, write content, append information, or perform other file operations. When file processing is complete, the file should be closed to release resources and help ensure that pending output is properly written.
Python supports two common approaches to closing files:
- Calling the
close() method explicitly.
- Using a
with statement, which closes the file automatically when the block finishes.
2. Learning Objectives
After completing this topic, learners should be able to:
- Understand the purpose of file handling.
- Use the
open() function with appropriate arguments.
- Identify different file opening modes.
- Open text and binary files correctly.
- Close files safely using
close().
- Use the
with statement for automatic file closure.
- Recognize common file-handling errors and handle them appropriately.
- Apply file opening and closing techniques in practical Python programs.
3. What Is the open() Function?
The open() function is a built-in Python function used to access a file. It returns a file object, which provides methods for reading, writing, and managing the file.
Syntax
file_object = open(file, mode='r', encoding=None)
The function supports additional optional parameters, including buffering, error handling for encoding and newline processing. The most commonly used arguments are the filename, mode, and encoding.
Explanation of the Arguments
| Argument |
Description |
Example |
file |
The filename or path of the file to open. |
"notes.txt" |
mode |
Specifies whether the file is opened for reading, writing, appending, or another operation. |
"r" |
encoding |
Specifies how text is decoded or encoded when working in text mode. |
encoding="utf-8" |
Example: Opening a File
file = open("notes.txt", "r", encoding="utf-8")
print("File opened successfully")
file.close()
Explanation:
open() attempts to open notes.txt in read mode.
- The returned file object is assigned to the variable
file.
- The message is printed if opening succeeds.
file.close() closes the file.
Important: In read mode, the file must already exist. If it cannot be found at the specified path, Python raises FileNotFoundError.
4. Understanding File Opening Modes
The mode determines how Python accesses a file. Choosing the correct mode is important because some modes can erase existing content or create a new file.
| Mode |
Purpose |
File Exists? |
Effect |
r |
Read text |
Must exist |
Reads existing content. |
w |
Write text |
Optional |
Creates a file if necessary or truncates an existing file. |
a |
Append text |
Optional |
Creates a file if necessary and adds content at the end. |
x |
Create exclusively |
Must not exist |
Creates a new file or raises FileExistsError. |
r+ |
Read and write |
Must exist |
Allows reading and writing without initially truncating the file. |
w+ |
Read and write |
Optional |
Creates or truncates the file. |
a+ |
Read and append |
Optional |
Creates the file if needed and writes at the end. |
rb |
Read binary |
Must exist |
Reads bytes rather than decoded text. |
wb |
Write binary |
Optional |
Creates or truncates a binary file. |
ab |
Append binary |
Optional |
Appends bytes to a binary file. |
Example: Read Mode
file = open("notes.txt", "r", encoding="utf-8")
content = file.read()
print(content)
file.close()
This example reads the entire text file into a string and prints its contents. The file must exist before the program runs.
Example: Write Mode
file = open("notes.txt", "w", encoding="utf-8")
file.write("Welcome to Python file handling.")
file.close()
This creates notes.txt if it does not exist. If the file already contains information, write mode removes the existing content before writing the new text. Use this mode carefully.
Example: Append Mode
file = open("notes.txt", "a", encoding="utf-8")
file.write("\nThis is an additional line.")
file.close()
Append mode preserves existing content and adds new content at the end of the file.
5. Understanding File Objects
A file object represents an opened file and provides methods and attributes for working with it. The object remains usable while the file is open and supports only the operations allowed by its opening mode.
Useful File Object Attributes
| Attribute |
Description |
name |
Provides the name or path associated with the file object. |
mode |
Indicates the mode used to open the file. |
closed |
Returns True if the file is closed and False if it is open. |
Example: Inspecting a File Object
file = open("notes.txt", "w", encoding="utf-8")
print("File name:", file.name)
print("File mode:", file.mode)
print("Is file closed?", file.closed)
file.close()
print("Is file closed now?", file.closed)
Possible output:
File name: notes.txt
File mode: w
Is file closed? False
Is file closed now? True
The exact path displayed by file.name may vary depending on the path supplied when opening the file.
6. Why Is Closing a File Important?
Closing a file ends the program's active connection to that file. It also helps release operating-system resources and ensures that buffered output is flushed as part of the normal closing process.
Closing files is important for several reasons:
- Resource management: Open files consume system resources.
- Reliable writing: Buffered data may not be fully written until it is flushed or the file is closed.
- File access: Proper closure helps prevent resource conflicts and makes it easier for other operations to use the file.
- Program stability: Applications that leave many files open may eventually encounter resource limitations.
- Clear program structure: Explicit file lifecycle management makes code easier to understand and maintain.
7. Closing Files Using close()
The close() method closes an open file object. After closure, the file object can no longer be used for normal reading or writing operations.
Syntax
file_object.close()
Example
file = open("report.txt", "w", encoding="utf-8")
file.write("Monthly report created successfully.")
file.close()
print("File closed:", file.closed)
Output:
File closed: True
The program opens a file, writes a message, closes the file, and checks its status using the closed attribute.
What Happens If You Use a Closed File?
file = open("report.txt", "w", encoding="utf-8")
file.write("Sample text")
file.close()
file.write("More text")
This raises a ValueError because the program attempts to write to a closed file. Any operation that requires the file to be open will fail after closure.
8. Opening and Closing Files with the with Statement
Python provides the with statement to manage file resources automatically. It is generally the recommended approach because Python closes the file when execution leaves the block, including when an exception occurs inside it.
Syntax
with open("filename.txt", "mode", encoding="utf-8") as file:
# Perform file operations here
pass
Example: Writing with with
with open("welcome.txt", "w", encoding="utf-8") as file:
file.write("Welcome to Python programming.")
file.write("\nLearn file handling step by step.")
print("File processing completed.")
Python automatically closes the file when the indented block ends. You do not need to call close() manually in this pattern.
Example: Reading with with
with open("welcome.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
print("File closed automatically after the block.")
Output:
Welcome to Python programming.
Learn file handling step by step.
File closed automatically after the block.
Checking Automatic Closure
with open("welcome.txt", "r", encoding="utf-8") as file:
print("Inside block:", file.closed)
print("Outside block:", file.closed)
Possible output:
Inside block: False
Outside block: True
9. Difference Between close() and with
| Feature |
Using close() |
Using with |
| Closure |
Must be called explicitly. |
Closes automatically after the block. |
| Exception safety |
Requires additional handling to ensure closure if an exception occurs. |
Closes the file even if an exception occurs inside the block. |
| Code length |
May require more statements. |
Usually shorter and easier to maintain. |
| Best use |
Useful when managing a file manually. |
Preferred for most ordinary file operations. |
10. Opening Files with an Explicit Encoding
When opening text files, specifying an encoding helps ensure that characters are interpreted consistently across different environments. UTF-8 is a widely used choice for modern text files.
Example
with open("message.txt", "w", encoding="utf-8") as file:
file.write("Hello, Python!")
file.write("\nLearning file handling is useful.")
file.write("\nPython supports Unicode: café, नमस्ते")
Using encoding="utf-8" helps preserve Unicode characters when the file is read or written in a compatible text environment. The encoding parameter applies to text mode, not binary mode.
11. Opening Files Using Relative and Absolute Paths
A file can be opened using either a relative path or an absolute path.
Relative Path
A relative path identifies a file in relation to the program's current working directory.
with open("data.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
The program searches for data.txt relative to the current working directory. That directory is not necessarily the same as the folder containing the Python script.
Absolute Path
An absolute path specifies the file's location from a filesystem root or drive.
# Example for Windows
with open(r"C:\Users\Student\Documents\data.txt",
"r",
encoding="utf-8") as file:
print(file.read())
The raw string prefix r helps prevent backslashes in a Windows path from being interpreted as escape sequences. Replace the example path with a real path on your computer.
12. Opening a File in Binary Mode
Binary mode is used for files whose content should be handled as bytes rather than decoded text. Examples include images, audio, video, PDFs, and other binary formats.
Example
with open("image.png", "rb") as file:
binary_data = file.read()
print(type(binary_data))
print("Bytes read:", len(binary_data))
Possible output:
<class 'bytes'>
Bytes read: 2048
The number of bytes depends on the actual file. The example assumes that image.png exists and contains data.
Do not specify encoding when opening a file in binary mode. Binary files should not be treated as ordinary text because doing so can corrupt or misinterpret their contents.
13. Handling File-Opening Errors
File operations may fail because of missing files, invalid paths, insufficient permissions, or other input/output problems. Python raises exceptions when such failures occur.
| Exception |
Common Cause |
Suggested Response |
FileNotFoundError |
The requested file or path does not exist. |
Check the filename and path, or create the file if appropriate. |
PermissionError |
The program lacks the required permission. |
Check file permissions and access restrictions. |
FileExistsError |
Exclusive creation mode x was used for an existing file. |
Choose another filename or handle the existing file intentionally. |
IsADirectoryError |
A directory was supplied where a file was expected. |
Verify that the path identifies a file. |
ValueError |
An operation is attempted on a closed file or an argument is invalid. |
Check the file lifecycle and function arguments. |
OSError |
A general operating-system or file I/O problem occurs. |
Inspect the error message and correct the underlying issue. |
Example: Handling a Missing File
try:
with open("missing.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("Error: The requested file was not found.")
This program handles the specific error that occurs when the requested file cannot be found.
Example: Handling Multiple File Errors
try:
with open("data.txt", "r", encoding="utf-8") as file:
print(file.read())
except FileNotFoundError:
print("The file does not exist.")
except PermissionError:
print("You do not have permission to access this file.")
except OSError as error:
print("A file operation failed:", error)
Specific exceptions are handled before the broader OSError handler so the program can provide more useful error messages.
14. Best Practices for Opening and Closing Files
- Prefer the
with open(...) pattern for normal file operations.
- Use an appropriate file mode for the task.
- Remember that
w truncates an existing file.
- Use
a when you want to preserve existing content and add new data.
- Specify
encoding="utf-8" when working with text files unless another encoding is required.
- Use binary mode for images and other non-text formats.
- Validate file paths and handle expected exceptions.
- Avoid opening files unnecessarily or leaving them open longer than needed.
- Do not attempt to read from or write to a file after it has been closed.
- Use clear variable names such as
file, input_file, or output_file.
- Be careful with file paths supplied by users, especially when applications access sensitive directories.
15. Common Mistakes and How to Fix Them
| Mistake |
Why It Happens |
Correction |
Opening a nonexistent file in r mode |
Read mode does not create a missing file. |
Check that the file exists or use an appropriate creation mode. |
Using w when existing content must be preserved |
Write mode truncates the file. |
Use a to append or select another suitable approach. |
| Forgetting to close a manually opened file |
The program does not release the file promptly. |
Call close() reliably or use with. |
| Writing to a closed file |
The file object's lifecycle has ended. |
Open the file again before performing another operation. |
| Using text mode for binary data |
Binary bytes may be decoded or transformed incorrectly. |
Use modes such as rb or wb. |
| Ignoring character encoding |
Text may display incorrectly or decoding may fail. |
Specify the correct encoding, commonly UTF-8. |
16. Practical Example: Creating and Reading a Student Record
This example demonstrates opening, writing, closing, reopening, and reading a text file using a safe context-manager approach.
# Step 1: Write student information to a file
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Name: Aarav\n")
file.write("Course: Python Programming\n")
file.write("Status: Enrolled\n")
print("Student record saved.")
# Step 2: Open the same file and read its contents
with open("student.txt", "r", encoding="utf-8") as file:
record = file.read()
print("\nStudent Record:")
print(record)
Output:
Student record saved.
Student Record:
Name: Aarav
Course: Python Programming
Status: Enrolled
How it works:
- The first
with block opens the file in write mode.
- The program writes three lines of student information.
- The file closes automatically when the first block ends.
- The second
with block opens the file in read mode.
- The program reads and displays the saved information.
- The file closes automatically when the second block ends.
17. Practical Example: Appending Information to a Log File
Applications often store events, updates, and status messages in log files. Append mode is useful when new messages should be added without deleting earlier records.
from datetime import datetime
log_message = f"Program executed at {datetime.now()}\n"
with open("application.log", "a", encoding="utf-8") as file:
file.write(log_message)
print("Log entry added successfully.")
Each execution adds another entry to application.log, assuming the program has permission to write to the destination.
18. Manual Closure with try and finally
Although the with statement is generally preferable, a try and finally structure can ensure that a manually opened file is closed even if an error occurs during processing.
file = open("report.txt", "r", encoding="utf-8")
try:
content = file.read()
print(content)
finally:
file.close()
The finally block executes whether reading succeeds or an exception occurs after the file has opened. For ordinary file handling, the equivalent with statement is usually simpler.
19. Mini Project: Simple Notes Manager
Objective: Build a small program that creates a notes file, adds new notes, and displays saved notes. This project practices file modes, file closure, and basic exception handling.
Project Code
def add_note():
note = input("Enter your note: ")
with open("my_notes.txt", "a", encoding="utf-8") as file:
file.write(note + "\n")
print("Note saved successfully.")
def view_notes():
try:
with open("my_notes.txt", "r", encoding="utf-8") as file:
notes = file.read()
if notes.strip():
print("\nYour Notes:")
print(notes)
else:
print("No notes available.")
except FileNotFoundError:
print("No notes file exists yet. Add a note first.")
while True:
print("\n1. Add Note")
print("2. View Notes")
print("3. Exit")
choice = input("Choose an option: ")
if choice == "1":
add_note()
elif choice == "2":
view_notes()
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid option. Please try again.")
Project Features
- Creates the notes file when the first note is added.
- Uses append mode to preserve earlier notes.
- Uses read mode to display saved notes.
- Uses
with to close files automatically.
- Handles the situation where the notes file does not yet exist.
- Provides a simple menu for interacting with the application.
20. Practice Exercises
- Create a file named
hello.txt and write a welcome message to it.
- Open an existing text file in read mode and display its contents.
- Write a program that appends three new lines to an existing file.
- Display the
name, mode, and closed attributes of a file object.
- Demonstrate how a file's
closed attribute changes after calling close().
- Write a program that handles
FileNotFoundError when reading a missing file.
- Create a new file using exclusive creation mode and handle
FileExistsError.
- Read a text file using a
with statement and UTF-8 encoding.
- Explain why write mode should be used carefully with existing files.
- Complete the Notes Manager mini project and test all menu options.
21. Interview Questions and Answers
Q1. What is the purpose of the open() function in Python?
Answer: The open() function opens a file and returns a file object that allows the program to read, write, append, or perform other supported operations.
Q2. What happens if the mode argument is omitted?
Answer: The default mode is r, which opens the file for reading text. The file must exist.
Q3. What is the difference between w and a modes?
Answer: The w mode truncates an existing file or creates a new one. The a mode preserves existing content and appends new content at the end.
Q4. Why should a file be closed after use?
Answer: Closing a file releases resources and helps ensure buffered output is written. It also prevents accidental use of a resource that is no longer needed.
Q5. What does close() do?
Answer: The close() method closes a file object. Operations that require the file to remain open will fail after it is closed.
Q6. Why is the with statement recommended?
Answer: It automatically closes the file when the block exits, even if an exception occurs. This reduces the risk of leaving files open.
Q7. What is a file object?
Answer: A file object is the object returned by open(). It provides methods and attributes for accessing and managing the opened file.
Q8. What is the difference between text mode and binary mode?
Answer: Text mode works with strings and character encoding. Binary mode works with bytes and is appropriate for files such as images and other non-text formats.
Q9. What happens when a missing file is opened in read mode?
Answer: Python raises FileNotFoundError if the requested file cannot be found.
Q10. Can a closed file object be reused for reading?
Answer: No. A closed file object cannot be used for normal file operations. The file must be opened again to continue working with it.
Q11. Why specify encoding="utf-8"?
Answer: It makes the intended text encoding explicit and helps text files containing international characters be read and written consistently.
Q12. What is the difference between a relative path and an absolute path?
Answer: A relative path is resolved from the current working directory, whereas an absolute path specifies the file's full location.
22. Quick Revision Checklist
open() opens a file and returns a file object.
r reads, w writes and truncates, and a appends.
x creates a file only if it does not already exist.
b indicates binary mode.
encoding="utf-8" is a useful explicit choice for text files.
close() closes a manually opened file.
with open(...) closes the file automatically after the block.
file.closed indicates whether the file object is closed.
FileNotFoundError can occur when a requested file is missing.
- Always choose the mode carefully to avoid accidental data loss.
23. Conclusion
Opening and closing files is a fundamental skill in Python programming. The open() function provides access to files, while its mode argument determines how the file can be used. The close() method allows explicit closure, and the with statement provides a safer, more convenient way to manage a file's lifecycle.
By practicing different modes, specifying text encodings, using appropriate file paths, and handling common exceptions, learners can build reliable programs that store and retrieve information effectively. The recommended habit for most everyday file operations is to use with open(...) and allow Python to close the file automatically.
24. Additional Learning Resources